<?php


namespace ApiWF\Controller;


use Common\Controller\ApibaseController;
use Think\Exception;
use Think\Log;


/**
 * 我的页面
 */
class MineController extends ApibaseController
{

    public function fetchUserInfo()
    {
        $uid = $this->parseTokenUID();


        $userInfo = D('Users')->where(['id' => $uid])->field('user_pass', true)->find();

        $userInfo['avatar'] = qiniu_mirror_image_url($userInfo['avatar']);


        $where = compact('uid');
        $userAttrInfo = D('UsersAttr')->where($where)->find();

        //可使用优惠券数量
        $where = [
            'uid' => $uid,
            'UsersCoupon.coupon_status' => 0,
            'Coupon.coupon_status' => ['GT',0],
            '_string' => 'UNIX_TIMESTAMP() < UNIX_TIMESTAMP(Coupon.end_time) AND UNIX_TIMESTAMP() > UNIX_TIMESTAMP(Coupon.start_time) ',
        ];
        $available_coupon_count = D('UsersCouponView')->where($where)->Count();
        $userInfo['available_coupon_count'] = $available_coupon_count;
        //未读消息

        $whereM = [
            'uid' => $uid,
            'is_read' => 0,
            'send_time' => ['LT', date('Y-m-d H:i:s')],
        ];
        $unread_message_count = D('UserMessages')->where($whereM)->Count();
        $userInfo['unread_message_count'] = $unread_message_count;

        //ss
        if (empty($userInfo)) {
            $this->error('非法token,未找到用户');
        } else {
            $userInfo['user_attr_info'] = $userAttrInfo;
            $this->jsonReturn($userInfo, '用户信息刷新成功!');
        }
    }

    //更新用户信息
    public function updateProfile()
    {
        $uid = $this->parseTokenUID();

        $User = D('Users');
        // 实例化User对象
        $UserAttr = D('UsersAttr'); // 实例化User对象

        $userinfo = I('post.');
        $userinfo = array_filter($userinfo);
        if (empty($userinfo)) {
            $this->success('个人信息未修改');
        }
        try {
            M()->startTrans();
            $User->where(['id' => $uid])->save($userinfo);
            $UserAttr->where(['uid' => $uid])->save($userinfo);
            M()->commit();

            $modeify_para = array_filter(I('param.'));

            $this->jsonReturn2($modeify_para);
        } catch (Exception $e) {
            M()->rollback();
            $this->error($e->getMessage());
        }


        // if ($User->create() and $UserAttr->create()) {
        //     $UserAttr->where(['uid' => $uid])->save(); // 写入数据到数据库
        //     $User->where(['id' => $uid])->save(); // 写入数据到数据库
        //     $this->success('用户信息更新成功,请刷新页面');
        // } else {
        //     $errorMsg = $User->getError();
        //     $errorMsg .= $UserAttr->getError();
        //     $this->error($errorMsg);
        // }

    }

    //获取反馈列表
    public function fetchSuggestionOptions()
    {
        $data = D('Suggestions')->select();
        $this->jsonReturn($data);
    }

    //提建议反馈
    public function submitSuggestion()
    {

        $uid = $this->parseTokenUID();

        $suggestion_id = I('suggestion_id');
        $suggestion_id_array = explode(',', $suggestion_id);


        $mobile = I('mobile');
        $pattern = '#^(13\d|14[57]|15[012356789]|18\d|17[013678])\d{8}$#';

        if (!preg_match($pattern, $mobile)) {
            $this->error('非法手机号码');
        }

        $model = D('UserSuggestions');
        $model->where(compact('uid'))->delete();
        $dataAll = [];
        foreach ($suggestion_id_array as $vo) {
            $dataAll[] = ['suggestion_id' => intval($vo), 'mobile' => $mobile, 'uid' => $uid];
        }

        try {
            $model->addAll($dataAll);
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 意见反馈
     * @return [type] [description]
     */
    public function advices()
    {
        $token = I('token', null);
        if (empty($token)) {
            $this->error('token 不能为空');
        }
        $uid = $this->parseTokenUID();


        // $mobile = I('mobile');
        // $pattern = '#^(13\d|14[57]|15[012356789]|18\d|17[013678])\d{8}$#';

        // if (!preg_match($pattern, $mobile)) {
        //     $this->error('非法手机号码');
        // }
        $user_advices = I('user_advices');
        $create_time = date("Y-m-d H:i:s", time());
        $data = compact('uid', 'user_advices', 'status', 'create_time');

        try {
            D('UserAdvices')->add($data);
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    //我的优惠劵
    public function mineCoupon()
    {
        $uid = $this->parseTokenUID();
        //优惠劵

        //未使用
        $where1 = [
            'uid' => $uid,
            'UsersCoupon.coupon_status' => 0,
            '_string' => ' UNIX_TIMESTAMP() > UNIX_TIMESTAMP(Coupon.start_time) AND UNIX_TIMESTAMP() < UNIX_TIMESTAMP(Coupon.end_time)',
            'Coupon.coupon_status' =>['GT',0]
        ];
        //未生效
        $where2 = [
            'uid' => $uid,
            'UsersCoupon.coupon_status' => 0,
            '_string' => ' UNIX_TIMESTAMP() < UNIX_TIMESTAMP(Coupon.start_time)',
            'Coupon.coupon_status' =>['GT',0]

        ];
        //已使用
        $where3 = [
            'uid' => $uid,
            'UsersCoupon.coupon_status' => 1,
            'Coupon.coupon_status' =>['GT',0]
        ];
        //已过期
        $where4 = [
            'uid' => $uid,
            'UsersCoupon.coupon_status' => 0,
            '_string' => ' UNIX_TIMESTAMP() > UNIX_TIMESTAMP(Coupon.end_time)',
            'Coupon.coupon_status' =>['GT',0]
        ];
        $model = D('UsersCouponView');
        $coupon1 = $model->where($where1)->order(['Coupon.end_time' => 'asc'])->select();        //未使用
        $coupon2 = $model->where($where2)->order(['Coupon.start_time' => 'asc'])->select();        //未生效
        $coupon3 = $model->where($where3)->order(['UsersCoupon.apply_time' => 'desc'])->select();        //已使用
        $coupon4 = $model->where($where4)->order(['Coupon.end_time' => 'desc'])->select();        //已过期
        $userCoupons = array_merge($coupon1, $coupon2, $coupon3, $coupon4);

        //其实有更有效的方法
        foreach ($userCoupons as $key => $coupon) {
            $userCoupons[$key]['coupon_pic'] = qiniu_mirror_image_url_coupon($coupon);
            $end_time = strtotime($coupon['end_time']);
            $start_time = strtotime($coupon['start_time']);
            $cTime = time();
            if ($start_time > $cTime) {
                //优惠券未启用(未生效)
                $userCoupons[$key]['is_expire'] = -1;
            } else if ($end_time < $cTime) {
                //已过期
                $userCoupons[$key]['is_expire'] = 1;
            } else {
                //可以使用
                $userCoupons[$key]['is_expire'] = 0;
            }

        }
        $this->jsonReturn($userCoupons);
    }

    //优惠券详情
    public function couponDetail()
    {

        $uid = $this->parseTokenUID();

        $id = I('user_coupon_id', 0, 'intval');
        //优惠劵
        $where = compact('uid', 'id');
        $where['Coupon.coupon_status'] = 1;
        $coupon = D('UsersCouponView')->where($where)->order('create_time desc')->find();
        if (!empty($coupon)) {
            $coupon['coupon_pic'] = qiniu_mirror_image_url_coupon($coupon);
            $end_time = strtotime($coupon['end_time']);
            $start_time = strtotime($coupon['start_time']);
            $cTime = time();
            if ($start_time > $cTime) {
                //优惠券未启用(未生效)
                $coupon['is_expire'] = -1;
            } else if ($end_time < $cTime) {
                //已过期
                $coupon['is_expire'] = 1;
            } else {
                //可以使用
                $coupon['is_expire'] = 0;
            }
            htmlStringToPlainStirngArray($coupon, 'coupon_description');
        } else {
            $this->error('优惠劵不存在');
        }
        $this->jsonReturn($coupon);
    }


    //删除优惠劵
    public function deleteCoupon()
    {
        $uid = $this->parseTokenUID();
        $id = I('coupon_id', 0, 'intval');
        //优惠劵
        $res = D('UsersCoupon')->where(compact('id', 'uid'))->delete();
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    //我的收藏
    public function mineFavorites()
    {
        $uid = $this->parseTokenUID();

        $condition = ['uid'=>$uid,'Activity.act_status'=>['GT',0]];
        //收藏活动
        $userActivityFavorites = D('UserActivityFavoritesView')->where($condition)->order('create_time desc')->select();
        foreach ($userActivityFavorites as $key => $vo) {
            $userActivityFavorites[$key]['act_pic'] = qiniu_mirror_image_url_act($vo);
            //act_content
            htmlStringToPlainStirngArray($userActivityFavorites[$key], 'act_content');
        }

        //我的点赞商户ids
        $praise_merch_ids = D('MerchUserPraises')->where(compact('uid'))->field('mid')->select();
        $praise_merch_ids = array_column($praise_merch_ids, 'mid');
        //收藏商户
        $mWhere = ['uid'=>$uid,'Merch.merch_status'=>['GT',0]];

        $userMerchFavorites = D('UserMerchFavoritesView')->where($mWhere)->order('create_time desc')->select();
        foreach ($userMerchFavorites as $key => $vo) {
            $userMerchFavorites[$key]['merch_pics'] = qiniu_mirror_image_url_merchant($vo);
            //判断是否已经点赞
            $res = in_array($vo['mid'], $praise_merch_ids);
            $userMerchFavorites[$key]['is_already_praised'] = $res ? 1 : 0;
        }
        $data['merch_favorites'] = $userMerchFavorites;
        $data['act_favorites'] = $userActivityFavorites;

        $this->json_doc = ['is_already_praised' => '1:已经点赞,0没有点赞'];
        $this->jsonReturn($data);
    }

    //删除我的优惠劵
    public function deleteFavorite()
    {
        $id = I('favorate_id', 0, 'intval');
        $type = I('type', 0, 'intval');
        $uid = $this->parseTokenUID();
        try {
            if ($type == 1) {
                //删除活动收藏
                //$where = ['uid'=>$uid,'id'=>]
                D('UserActivityFavorites')->where(compact('uid', 'id'))->delete();
            }
            if ($type == 2) {
                //删除商铺收藏
                D('UserMerchFavorites')->where(compact('uid', 'id'))->delete();
            }
            $this->success();
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->error();
    }

    public function mineCoinRecords()
    {
        $uid = $this->parseTokenUID();

        //金币记录
        $coin_records = D('UsersCoinRecord')->where(compact('uid'))->order('update_time desc')->select();
        foreach ($coin_records as $key => $vo) {


        }
        $this->jsonReturn($coin_records);
    }

    //我的金币消费记录
    public function mineCoinRecordsPagination()
    {
        $uid = $this->parseTokenUID();
        $where = compact('uid');
        $order = 'update_time desc';
        $model = D('UsersCoinRecord');
        $data = $this->pageHelper($model, $where, $order);
        $list = $data['list'];
        foreach ($list as $key => $vo) {
            $int = intval($vo['coin']);
            if ($int > 0) {
                $list[$key]['coin'] = '+' . $vo['coin'];
            }
        }
        $data['list'] = $list;
        $this->jsonReturn($data);
    }

}